package com.longqinuo.mycarservice.fragments;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.longqinuo.mycarservice.R;
import com.longqinuo.mycarservice.utils.PathUtils;
import com.longqinuo.mycarservice.view.LruImageCache;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link MoreConfigFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MoreConfigFragment extends Fragment implements View.OnClickListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private static RequestQueue queue;
    private static ImageLoader imageLoader;
    private int mId;

    private OnFragmentInteractionListener mListener;
    private ImageView mBack;
    private TextView mTitle;
    private ImageView mOption;
    private ListView lv_more_config_list;
    private SimpleAdapter mAdapter;
    private List<Map<String, String>> mList;
    private String names[] = {"厂商", "级别", "发动机", "变速箱", "车身结构",
            "长*宽*高(mm)", "轴距(mm)", "行李箱容积(L)", "整备质量(kg)"};
    private String values[] = new String[9];
    private TextView tv_car_type_more;
    private TextView tv_year_more;
    private TextView tv_out_put_value;


    public MoreConfigFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment MoreConfigFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static MoreConfigFragment newInstance(String param1, String param2) {
        MoreConfigFragment fragment = new MoreConfigFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mId = Integer.valueOf(mParam1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        init();
    }

    private void init() {  //初始化操作
        queue = Volley.newRequestQueue(getActivity());
        LruImageCache lruImageCache = LruImageCache.instance();
        imageLoader = new ImageLoader(queue, lruImageCache);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_more_config, container, false);
        initView(view);
        return view;
    }

    private void initView(View view) {

        mBack = (ImageView) view.findViewById(R.id.iv_top_back);
        mBack.setOnClickListener(this);
        mTitle = (TextView) view.findViewById(R.id.tv_top_title);
        mTitle.setText("配置参数");
        mOption = (ImageView) view.findViewById(R.id.iv_top_option);
        mOption.setVisibility(View.INVISIBLE);
        lv_more_config_list = (ListView) view.findViewById(R.id.lv_more_config_list);
        initData();

        tv_car_type_more = (TextView) view.findViewById(R.id.tv_car_type_more);
        tv_year_more = (TextView) view.findViewById(R.id.tv_year_more);
        tv_out_put_value = (TextView) view.findViewById(R.id.tv_out_put_value);
    }

    private void initData() {
        mList = new ArrayList<>();

        mAdapter = new SimpleAdapter(getActivity(), mList,
                R.layout.more_config_item_layout,
                new String[]{"name", "value"},
                new int[]{R.id.tv_more_config_name, R.id.tv_more_config_value});
        lv_more_config_list.setAdapter(mAdapter);
        requestData();
    }
    private void requestData() {  //请求车辆详细数据
        JsonObjectRequest request = new JsonObjectRequest(PathUtils.CAR_CONFIG+"?id="+mId, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                try {
                    int code = jsonObject.getInt("code");
                    if (code==0) {
                        JSONObject o = jsonObject.getJSONObject("data");
                        String title = o.getString("title");
                        String strs[] = title.split(" ");
                        tv_car_type_more.setText(strs[0]);
                        String str = title.replace(strs[0],"");
                        tv_year_more.setText(str);

                        double outputValue = o.getDouble("outputValue");
                        tv_out_put_value.setText(outputValue+"");

                        String film = o.getString("film");
                        values[0] = film;

                        String level = o.getString("level");
                        values[1] = level;

                        String engine = o.getString("engine");
                        values[2] = engine;

                        String gearbox = o.getString("gearbox");
                        values[3] = gearbox+"变速器";

                        String structre = o.getString("structre");
                        values[4] = structre;

                        String volume = o.getString("volume");
                        values[5] = volume;
                        double wheelbase = o.getDouble("wheelbase");
                        values[6] = wheelbase+"";

                        double trunksize = o.getDouble("trunksize");
                        values[7] = trunksize+"";
                        double quality = o.getDouble("quality");
                        values[8] = quality+"";

                        for (int i = 0; i < names.length; i++) {
                            Map<String, String> map = new HashMap<>();
                            map.put("name", names[i]);
                            map.put("value", values[i]);
                            mList.add(map);
                        }
                        mAdapter.notifyDataSetChanged();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        });
        queue.add(request);
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_top_back:
                getActivity().getSupportFragmentManager().popBackStack();
                break;
        }

    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
